const Controller = require('egg').Controller;

class RoleController extends Controller {
  // 新增角色
  async role_add() {
    const query = this.ctx.request.body;
    const query_bol = this.ctx.helper.validInput(query, ['name', 'value']);
    if(query_bol != 'true') return query_bol;

    const params = {
      name: query.name,
      value: query.value,
      status: query.status,
      menus: query.menus,
      remark: query.remark
    };
    try {
      // 查询角色菜单权限
      const menuPermi = await this.ctx.service.menu.menu_findByIds(query.menus),
            permi = [];
      menuPermi.map(item => {
        if(item.permi) {
          permi.push(item.permi)
        }
      })
      params['permissions'] = permi;
      // 存入角色数据
      await this.ctx.service.role.role_add(params);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 1,
        m: 'ok~',
        d: {}
      };
    }catch(err) {
      return this.ctx.body = {
        s: 0,
        m: 'fail~',
        d: {}
      }
    }
  }
  // 更新角色
  async role_update() {
    const query = this.ctx.request.body;
    const query_bol = this.ctx.helper.validInput(query, ['id', 'name', 'value']);
    if(query_bol != 'true') return query_bol;

    const params = {
      name: query.name,
      value: query.value,
      status: query.status,
      menus: query.menus,
      remark: query.remark
    };
    try {
      // 查询角色菜单权限
      const menuPermi = await this.ctx.service.menu.menu_findByIds(query.menus),
            permi = [];
      menuPermi.map(item => {
        if(item.permi) {
          permi.push(item.permi)
        }
      })
      params['permissions'] = permi;
      // 存入角色数据
      await this.ctx.service.role.role_update(query.id, params);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 1,
        m: 'ok~',
        d: {}
      };
    }catch(err) {
      return this.ctx.body = {
        s: 0,
        m: 'fail~',
        d: {}
      }
    }
  }
  // 角色列表
  async role_list() {
    try {
      const roleRes = await this.ctx.service.role.role_list();
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 1,
        m: 'ok~',
        d: roleRes
      };
    }catch(err) {
      return this.ctx.body = {
        s: 0,
        m: `fail~${err}`,
        d: {}
      };
    }
  }
  // 删除角色
  async role_del() {
    const query = this.ctx.request.body;
    const query_bol = this.ctx.helper.validInput(query, ['id']);
    if(query_bol != 'true') return query_bol;

    try {
      await this.ctx.service.role.role_del(query.id);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 1,
        m: 'ok~',
        d: {}
      };
    }catch(err) {
      return this.ctx.body = {
        s: 0,
        m: `fail~${err}`,
        d: {}
      };
    }
  }
}

module.exports = RoleController;